package com.hinner.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hinner.common.Result;
import com.hinner.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qr")
public class QRCodeController {

    private final QRCodeUtil qrCodeUtil;

    @Autowired
    public QRCodeController(QRCodeUtil qrCodeUtil) {
        this.qrCodeUtil = qrCodeUtil;
    }

    /**
     * 后端生成二维码接口
     * @param content
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/{content}")
    public Result getQRCode(@PathVariable("content") String content, HttpServletResponse response) throws Exception {
        //内容
//        String content = "C2024061100107,18912899999";

        //二维码属性：误差矫正 、 字符集、四周留白
        Map map = new HashMap<>();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        map.put(EncodeHintType.MARGIN,1);
        
        // 核心对象，多格式写入器
        MultiFormatWriter writer = new MultiFormatWriter();
//        writer.encode(内容，格式，宽，高，内容)
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 300, 300, map);//位矩阵
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//二维码
        //遍历位矩阵
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                image.setRGB(i,j,bitMatrix.get(i,j) ? 0xFF000000:0xFFFFFFFF );
            }
        }
        OutputStream out = response.getOutputStream();

        ImageIO.write(image,"png",out);
        out.flush();
        out.close();
        return Result.success();
    }


    /**
     * 后端解析二维码接口
     * 本次前端传入的格式是  1432432423，432423423样式
     * @return
     */
    @PostMapping("/parse")
    public Result parseQRCode(@RequestParam("file") MultipartFile file) throws Exception {
        File convert = QRCodeUtil.convert(file);
        String analysis = qrCodeUtil.analysis(convert);
        return Result.success(Arrays.asList(analysis.split(",")));
    }


}
